/*
 * Hidden Equity LLC
 * Author: Maksym Fedyay, Kyiv, mcsimf@gmail.com
 * Date: 29.02.2012
 */

package com.hiddenequity.utils;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XMLUtils {
	
	
	/*
	 * Convert string data to document
	 */
	static public Document XMLStringToDoc(String XMLData) throws ParserConfigurationException{
		try {
	        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	        DocumentBuilder db = dbf.newDocumentBuilder();
	        InputSource is = new InputSource();
	        is.setCharacterStream(new StringReader(XMLData));
	        Document doc = db.parse(is);
	        doc.normalize();
	        return doc;
		} catch (IOException e) {
			return null;
		} catch (SAXException  e) {
			e.getMessage();
			return null;
		}
	}//XMLStringToDoc
	

	
	/*
	 * Get data from XML tag
	 */
	public static String getCharacterDataFromElement(Element element) {
		Node child = null;
		
		try {
			child = element.getFirstChild();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if (child instanceof CharacterData) {
			CharacterData cd = (CharacterData) child;
		   	return (String) cd.getData();
		} else {
			return null;
		}
	}//getCharacterDataFromElement

}
